package com.guilin.controller;

import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.guilin.common.exception.ServiceException;
import com.guilin.common.utils.SecurityUtils;
import com.guilin.domain.Alumni;
import com.guilin.system.service.AlumniService;
import com.guilin.system.service.CareerDestinationService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.guilin.common.core.controller.BaseController;
import com.guilin.common.core.domain.AjaxResult;
import com.guilin.domain.CareerDestination;
import com.guilin.common.utils.poi.ExcelUtil;
import com.guilin.common.core.page.TableDataInfo;

/**
 * 毕业去向Controller
 *
 * @author xiaoqi
 * @date 2025-06-23
 */
@RestController
@RequestMapping("/admin-management/destination")
public class CareerDestinationController extends BaseController
{
    @Autowired
    private CareerDestinationService careerDestinationService;

    @Autowired
    private AlumniService alumniService;

    /**
     * 查询毕业去向列表
     */
    @PreAuthorize("@ss.hasPermi('admin-management:destination:list')")
    @GetMapping("/list")
    public TableDataInfo list(CareerDestination careerDestination)
    {
        startPage();
        List<CareerDestination> list = careerDestinationService.selectCareerDestinationList(careerDestination);
        return getDataTable(list);
    }

    /**
     * 导出毕业去向列表
     */
    @PreAuthorize("@ss.hasPermi('admin-management:destination:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, CareerDestination careerDestination)
    {
        List<CareerDestination> list = careerDestinationService.selectCareerDestinationList(careerDestination);
        ExcelUtil<CareerDestination> util = new ExcelUtil<CareerDestination>(CareerDestination.class);
        util.exportExcel(response, list, "毕业去向数据");
    }

    /**
     * 获取毕业去向详细信息
     */
    @PreAuthorize("@ss.hasPermi('admin-management:destination:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(careerDestinationService.selectCareerDestinationById(id));
    }

    /**
     * 新增毕业去向
     */
    @PreAuthorize("@ss.hasPermi('admin-management:destination:add')")
    @PostMapping
    public AjaxResult add(@RequestBody CareerDestination careerDestination)
    {
        // 管理员操作时，必须指定校友ID
        if (careerDestination.getAlumniId() == null) {
            return AjaxResult.error("新增毕业去向必须指定校友ID");
        }

        // 检查该校友是否已有记录
        CareerDestination existing = careerDestinationService.selectByAlumniId(careerDestination.getAlumniId());

        if (existing != null) {
            return AjaxResult.error("该校友已有毕业去向记录，添加失败!");
        }

        return toAjax(careerDestinationService.insertCareerDestination(careerDestination));
    }

    /**
     * 修改毕业去向
     */
    @PreAuthorize("@ss.hasPermi('admin-management:destination:edit')")
    @PutMapping
    public AjaxResult edit(@RequestBody CareerDestination careerDestination)
    {
        // 检查校友ID是否变更
        if (careerDestination.getId() != null) {

            CareerDestination oldRecord = careerDestinationService.selectCareerDestinationById(careerDestination.getId());

            // 避免一个校友有多条毕业去向
            if (oldRecord != null && !oldRecord.getAlumniId().equals(careerDestination.getAlumniId())) {

                return AjaxResult.error("不允许修改校友ID");

            }
        }

        return toAjax(careerDestinationService.updateCareerDestination(careerDestination));
    }

    /**
     * 删除毕业去向
     */
    @PreAuthorize("@ss.hasPermi('admin-management:destination:remove')")
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(careerDestinationService.deleteCareerDestinationByIds(ids));
    }


    /**
     * 获取职业类别分类统计
     * @return
     */
    @PreAuthorize("@ss.hasPermi('admin-management:destination:statistics')")
    @GetMapping("/categoryStatistics")
    public AjaxResult getCategoryStatistics(){

        List<Map<String, Object>> statistics = careerDestinationService.countByCategory();
        return success(statistics);
    }


    /**
     * 前台
     */

    /**
     * 获取个人毕业去向
     */
    @PreAuthorize("@ss.hasPermi('admin-management:destination:query')")
    @GetMapping("/personal/{alumniId}")
    public AjaxResult getPersonalDestination(@PathVariable("alumniId") Long alumniId) {

        CareerDestination destination = careerDestinationService.selectByAlumniId(alumniId);

        return success(destination);
    }

    /**
     * 新增或更新当前校友的毕业去向
     */
    @PreAuthorize("@ss.hasPermi('admin-management:destination:edit')")
    @PostMapping("/personalDestination")
    public AjaxResult saveMyCareerDestination(@RequestBody CareerDestination careerDestination) {

        // 获取当前登录用户
        Long userId = SecurityUtils.getLoginUser().getUserId();

        // 查找当前用户的校友信息
        Alumni alumni = alumniService.selectUserId(userId);

        // 检查校友信息是否存在
        if (alumni == null) {
            throw new ServiceException("校友信息不存在");
        }

        // 获取校友ID
        Long alumniId = alumni.getId();

        // 设置校友ID
        careerDestination.setAlumniId(alumniId);

        // 检查是否已存在记录
        CareerDestination existing = careerDestinationService.selectByAlumniId(alumniId);

        if (existing == null) {

            // 新增记录
            return toAjax(careerDestinationService.insertCareerDestination(careerDestination));

        } else {

            // 更新记录
            careerDestination.setId(existing.getId());

            return toAjax(careerDestinationService.updateCareerDestination(careerDestination));
        }
    }
}
